package com.tt5.services.vertx

import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpServerRequest
import io.vertx.ext.web.RoutingContext
import io.vertx.redis.client.Redis
import io.vertx.sqlclient.Pool
import io.vertx.sqlclient.PoolOptions

const val keyTraceId = "trace_id"
var RoutingContext.traceId: String
  get() {
    return get(keyTraceId)
  }
  set(value) {
    put(keyTraceId, value)
  }

/**
 * 获取[name]对应的共享数据库连接池，需保证在使用前已经初始化
 */
fun RoutingContext.sharedDbPool(name: String = PoolOptions.DEFAULT_NAME): Pool = vertx().sharedDbPool(name)

val RoutingContext.redis: Redis
  get() = vertx().redis

fun RoutingContext.text(text: String) {
  response().putHeader(
    HttpHeaders.CONTENT_TYPE, "text/plain; charset=utf-8"
  ).end(text)
}

fun RoutingContext.requestToString(lineSeparator: String = ", ") = buildString {
  append("Uri: ${request().uri()}")
  append("${lineSeparator}Method: ${request().method()}")
  append("${lineSeparator}Headers: [${request().headers().joinToString(", ")}]")
  if (body().length() > 0) {
    val contentType = parsedHeaders().contentType()
    val type = contentType.subComponent().lowercase()
    if (type.contains("json") || type.contains("xml") || type.contains("text/plain")) append(
      "${lineSeparator}Body: ${body().asString()}"
    ) else append("-----decoded body[${body().length()}]-----")
  }
}

fun RoutingContext.responseToString(lineSeparator: String = ", ") = buildString {
  append("Uri: ${request().uri()}")
  append("${lineSeparator}Method: ${request().method()}")
  append("${lineSeparator}Status: ${response().statusCode}")
  append("${lineSeparator}Headers: [${response().headers().joinToString(", ")}]")
  if (body().length() > 0) {
    val type = response().headers().get(HttpHeaders.CONTENT_TYPE)
    if (type.contains("json") || type.contains("xml") || type.contains("text/plain")) append(
      "${lineSeparator}Body: ${body().asString()}"
    ) else append("-----decoded body[${body().length()}]-----")
  }
}
